import axios from 'axios';
import { storeLib } from '@/utils/src/store';

const http = axios.create({
  applicationType: 'json',
  timeout: 1000 * 30,
  IfToken: true,
  ifkey: false,
  baseURL: 'https://saastest.itjyun.com/gateway',
  headers: {
    'User-Os': 'IM/PC',
  },
});

http.interceptors.request.use(
  config => {
    if (config.ifkey) {
      config.headers['Authorization'] = 'Basic ZmViczoxMjM0NTY=';
    } else if (!config.ifkey && config.IfToken) {
      const tokenData = storeLib.get('tokenData');
      tokenData && (config.headers['Authorization'] = 'bearer ' + tokenData.access_token);
    }

    if (config.noOSKey) {
      delete config.headers['User-Os'];
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  },
);

http.interceptors.response.use(res => {
  if (res.config.url === '/authcenter/oauth/token') {
    return res.data;
  }
  if (res.data.code !== 200) {
    return Promise.reject(res.data);
  }
  return res.data;
});

export default http;
